#include "CKThreadPool.h"



namespace K_Engine
{
	CKThreadPool::CKThreadPool() :
		m_nPoolSize(-1),
		bIsStart(false)
	{
	}
	
	
	bool CKThreadPool::SetThreadNum(int size)
	{
		if( 0 >= size )
		{
			SetLastError("启动线程数量出错，不允许小于或等于0");
			return false;
		}
		else
		{
			m_nPoolSize = size;
			return true;
		}
	}
	
	
	bool CKThreadPool::Start(void* rcb, resultCallBack _resultcallback)
	{
		if(bIsStart)
		{
			SetLastError("线程池已启动工作");
			return false;
		}
		else
		{
			if( 0 >= m_nPoolSize )
			{
				SetLastError("启动线程数量出错，不允许小于或等于0");
				return false;
			}
			else
			{
				popworkCallBack _callback = (popworkCallBack)(&CKThreadPool::GetWork);
				for(int i = 0 ; i < m_nPoolSize ; i ++)
				{
					m_thread.push_back(new CKThread(_callback, this, _resultcallback, rcb));
				}
				return true;
			}	
		}	
	}
	
	
	void CKThreadPool::SetLastError(std::string strError)
	{
		strLastError.clear();
		strLastError = strError;
	}
	
	
	std::string CKThreadPool::strGetLastError() const
	{
		return strLastError;
	}
	
	
	CKThreadPool::~CKThreadPool()
	{
		int size = m_thread.size();
		for(int i = 0 ; i < size ; i++)
		{
			//退出线程
			m_thread[i]->ChangeIsAlive(false);
		}
		m_work.JustReturnWait();
		for(int i = 0 ; i < size ; i++)
		{
			//删除线程并join等待线程退出
			delete m_thread[i];
		}
			
		
		for(int i = 0 ; i < size ; i++)
		{
			//压入NULL
			//让可能还在阻塞的线程返回退出
			m_work.Push("");
		}
		m_thread.clear();
		m_work.Clear();
	}
	
	
	void CKThreadPool::SetWork(std::string _work)
	{
		m_work.Push(_work);
	}
	
	
	std::string CKThreadPool::GetWork()
	{
		return m_work.Pop();
	}
}
